var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
let articleRouter = require('./routes/article');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

/*引用session
* */
let session = require('express-session')
/*
*session配置
* */
app.use(session({
    secret: "keyboard cat",
    resave: false,
    saveUninitialized: true,
    //maxAge:最多可以存活多久
    cookie: ('name', 'value', {maxAge: 5 * 60 * 1000, secure: false})
}))
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

/**
 * 定义全局的加解密密钥
 * @type {string}
 */
global.globalKey = '123456';
let jwtUtil = require('./utils/jwtUtils');
let redisUtils = require('./utils/redisUtils');

/**
 * 拦截器中间件
 */
app.use(async function (req, resp, next) {
    let path = req.path;
    // console.log(path)
    if (path.startsWith("/users")) {
        if (path.startsWith("/users/login") || path.startsWith("/users/regist")
            || path.startsWith("/users/getCaptcha")
            || path.startsWith("/users/captchaValid")
            || path.startsWith("/users/getUserName")

        ) {
            console.log("放行users")
            next()
            return
        }
        if (path.startsWith("/users/getHead")) {
            console.log("拦截头像")
            let token = await redisUtils.get("jwt_token")
            let result = await jwtUtil.verifysync(token, global.globalKey)
            if (result.err) {
                resp.send("游客")
                return
            } else {
                next();
                return
            }
        }
        console.log("拦截")
        let token = await redisUtils.get("jwt_token")
        let result = await jwtUtil.verifysync(token, global.globalKey)
        if (result.err) {
            jwtAtert(resp)
            return
        } else {
            req.headers.session = result
            next();
            return
        }
    }

    if (path.startsWith("/article")) {
        if (path.startsWith("/article/img")
            || path.startsWith("/article/getDetails")
            || path.startsWith("/article/addHist")
            || path.startsWith("/article/getComment")
            || path.startsWith("/article/getAll")

        ) {
            console.log("放行文章")
            next()
            return
        }
        console.log("拦截")
        let token = await redisUtils.get("jwt_token")
        let result = await jwtUtil.verifysync(token, global.globalKey)

        if (result.err) {
            jwtAtert(resp)
            return
        } else {
            req.headers.session = result
            next();
            return
        }
    }

    if (path.startsWith("/")) {
        if (path.startsWith("/setEM")) {
            let token = await redisUtils.get("jwt_token")
            let result = await jwtUtil.verifysync(token, global.globalKey)
            if (result.err) {
                jwtAtert(resp)
                return
            } else {
                req.headers.session = result
                next();
                return
            }
        } else {
            console.log("放行根目录")
            next()
            return
        }

    }
    next();

})

function jwtAtert(resp) {
    resp.status(500).send('该功能只能由登录用户使用,请前往登陆页面进行登录后使用')
}

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/article', articleRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
